package com.kingsoft.dc.khaos.plugin.core.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kingsoft.dc.khaos.plugin.core.KhaosConf;
import com.kingsoft.dc.khaos.plugin.core.exception.ParamParseException;
import com.kingsoft.dc.khaos.plugin.core.metadata.PluginModuleConfig;

import java.util.*;

/**
 * Created by jing on 19/7/23.
 */
public class AppConfigParse {
    final private static String GRAPH = "graph";
    final private static String WIDGETS = "widgets";
    final private static String PLUGIN = "plugin_param";


    private KhaosConf conf;

    public AppConfigParse(KhaosConf conf) {
        this.conf = conf;
    }

    public List<PluginModuleConfig> parseJson(String jsonStr) throws Exception {
        //组件信息列表
        List<PluginModuleConfig> khaosInfo = new ArrayList<PluginModuleConfig>();
        Map<String, Object> configMap = new HashMap<>();
        try {
            configMap = JSON.parseObject(jsonStr, Map.class);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ParamParseException("参数格式错误,不是正确的json字符串,参数:" + jsonStr);
        }

        configMap.forEach((key, value) -> {
            conf.set(key, value);
        });
        Map moduleMap = new HashMap();
        if (JsonUtils.containsKey(configMap, GRAPH, WIDGETS)) {
            moduleMap = JsonUtils.extractListValue(configMap, Map.class, GRAPH, WIDGETS).get(0);
        } else if (JsonUtils.containsKey(configMap, PLUGIN)){
            moduleMap = JsonUtils.extractMapValue(configMap, PLUGIN);
        } else {
            throw new ParamParseException("has no module config,params has no key [" + PLUGIN + "] or [graph.widgets]");
        }
        String id = String.valueOf(moduleMap.get("id"));
        String name = String.valueOf(moduleMap.get("name"));
        String engine = String.valueOf(moduleMap.get("engine"));
        String clazz = String.valueOf(moduleMap.get("clazz"));
        String clazzType = String.valueOf(moduleMap.getOrDefault("clazz_type", "source"));
        String moduleConf = JSONObject.toJSONString(moduleMap.get("strategy"));
        PluginModuleConfig module = new PluginModuleConfig(
                id,
                name,
                engine,
                clazz,
                clazzType,
                moduleConf);
        conf.set(id, moduleConf);
        khaosInfo.add(module);
        return khaosInfo;
    }

}
